package com.example.thread.demo.alternate.print5;

import java.util.concurrent.Semaphore;

/**
 * 信号量解决多线程依次打印
 */
public class SemaphoreABC {

    private static Semaphore A = new Semaphore(1);// 以A开始的信号量，初始信号量数量为1
    private static Semaphore B = new Semaphore(0);
    private static Semaphore C = new Semaphore(0);

    class Runner implements Runnable {

        private final Semaphore current;
        private final Semaphore next;
        private final String content;

        public Runner(Semaphore current, Semaphore next, String content) {
            this.current = current;
            this.next = next;
            this.content = content;
        }

        @Override
        public void run() {
            try {
                for (int i = 0; i < 10; i++) {
                    current.acquire();// 当前的获取信号执行，信号量减1，当为0时将无法继续获得该信号量
                    System.out.println(Thread.currentThread().getName() + "---" + content);
                    next.release();// 当前的释放信号，信号量加1（初始为0），此时可以获取该信号量
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        SemaphoreABC semaphoreABC = new SemaphoreABC();
        Thread t1 = new Thread(semaphoreABC.new Runner(A, B, "A"));
        Thread t2 = new Thread(semaphoreABC.new Runner(B, C, "B"));
        Thread t3 = new Thread(semaphoreABC.new Runner(C, A, "C"));
        t1.start();
        t2.start();
        t3.start();
    }
}
